package com.usian.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.mapper.CourseMapper;
import com.usian.mapper.StudentMapper;
import com.usian.pojos.Course;
import com.usian.pojos.Student;
import com.usian.service.StudentService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void importFiel(MultipartFile importFile) {

        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(importFile.getInputStream());

            XSSFSheet sheetAt0 = workbook.getSheetAt(0);

            XSSFSheet sheetAt1 = workbook.getSheetAt(1);

            int rowNum0 = sheetAt0.getLastRowNum();

            List<Student> studentList = new ArrayList<>();

            for (int i = 1; i <= rowNum0; i++) {

                XSSFRow row = sheetAt0.getRow(i);

                String sname = row.getCell(0).getStringCellValue();

                int age = (int)row.getCell(1).getNumericCellValue();

                String sex = row.getCell(2).getStringCellValue();

                Student student = new Student();

                student.setSname(sname);

                student.setAge(age);

                student.setSex(sex);

                studentList.add(student);
            }
            studentMapper.importFile(studentList);

            int rowNum1 = sheetAt1.getLastRowNum();
            
            List<Course> courseList = new ArrayList<>();

            for (int i = 1; i <= rowNum1; i++) {

                XSSFRow row = sheetAt1.getRow(i);

                String cname = row.getCell(0).getStringCellValue();

                Course course = new Course();

                course.setCname(cname);

                courseList.add(course);
            }
            courseMapper.importFile(courseList);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
